package sign;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import properties.User;
import util.EmailSender;
import util.HttpRequest;
import util.WorkDayUtil;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author liufei
 * @Description
 * @Date 2020/11/10 19:20
 */
public class Signer {
    private static final Logger logger = LoggerFactory.getLogger(Signer.class);
    private static final String url = "oa.dragonit.com.cn:89";
    private static final Random random = new Random();
    private HttpRequest httpRequest = new HttpRequest();
    private User user;
    private boolean isWorkDay = true;


    public Signer(User user) {
        this.user = user;
        try {
            isWorkDay = WorkDayUtil.isWork(new Date());
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            String email = user.getEmail();
            EmailSender.send(false,"工作日判定异常:\n" + sw.toString(), email);
            logger.error("工作日判定异常", e);
        }
    }

    public Signer(String name, String pwd, String email, String sid, String mac) {
        this.user = new User(name, pwd, email, sid, mac);
    }

    public void login() throws Exception {
        if (!isWorkDay) {
            logger.info("今天不是工作日，不用打卡");
            return;
        }
        while (true) {
            Map<String, Object> map = new HashMap<>();
            map.put("isie", "false");
            map.put("islanguid", "7");
            map.put("logintype", "1");
            map.put("loginid", user.getName());
            map.put("userpassword", user.getPwd());
            map.put("dynamicPassword", "");
            CloseableHttpResponse response = httpRequest.post("http://" + url + "/api/hrm/login/checkLogin", map);
            HttpEntity post = response.getEntity();
            String resultMsg = EntityUtils.toString(post);
            if (response.getStatusLine().getStatusCode() <= 200 && !resultMsg.contains("失败") && !resultMsg.contains("错误")) {
                logger.info("[{}]登录成功", user.getName());
                break;
            }
            if (response.getStatusLine().getStatusCode() == 500) {
                logger.error("服务器异常[" + resultMsg + "]");
                throw new RuntimeException("服务器异常[" + resultMsg + "]");
            }
            if (resultMsg.contains("密码错误")) {
                logger.error("[{}]密码错误[{}]", user.getName(), resultMsg);
                throw new RuntimeException("[" + user.getName() + "]密码错误[" + resultMsg + "]");
            }
            logger.error("[{}]登录失败[{}]", user.getName(), resultMsg);
        }
    }

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");


    public void inSign() throws Exception {
        if (!isWorkDay) {
            return;
        }

        String sid = user.getSid();
        String mac = user.getMac();
        Map<String, Object> map1 = new HashMap<>();
        String format = sdf.format(new Date());
        map1.put("date", format);
        map1.put("belongtime", format);
        map1.put("isfirstsign", "1");
        map1.put("signSection", format + " 00:01:00#" + format + " 23:59:59");
        map1.put("signSectionTime", format + " 00:01:00");
        map1.put("active", "1");
        map1.put("time", "");
        map1.put("needSign", "1");
        map1.put("type", "on");
        map1.put("canSignTime", "00:00");
        map1.put("longitude", String.valueOf(118.04448) + String.valueOf(random.nextInt(784321787)));
        map1.put("latitude", String.valueOf(24.61422) + String.valueOf(random.nextInt(2068608887)));
        map1.put("position", "福建省厦门市集美区诚毅北大街55号靠近厦门国信信用大数据创新研究院");
        map1.put("locationid", "6");
        map1.put("locationshowaddress", "1");
        map1.put("sid", sid);
        map1.put("mac", mac);
        map1.put("deviceId", "863064396916522");
        map1.put("deviceInfo", "{\"errCode\":0,\"errMsg\":\"getClientInfo:ok\",\"clientType\":\"3\",\"clientVersion\":\"7.0.37.20200806\",\"deviceId\":\"863064396916522\",\"osVersion\":25,\"clientModel\":\"Xiaomi,MI 9\",\"clientFont\":\"1\",\"clientTheme\":\"#393F9D\",\"clientLang\":\"zh\",\"networkType\":\"wifi\",\"BSSID\":\"" + mac + "\",\"SSID\":\"" + sid + "\"}");
        map1.put("browser", "EMobile");
        map1.put("_ec_ismobile", "true");
        map1.put("_ec_browser", "EMobile");
        map1.put("_ec_browserVersion", "7.0.37.20200806");
        map1.put("_ec_os", "Android");
        map1.put("_ec_osVersion", "7.1.2");
        map1.put("ismobile", "1");
        CloseableHttpResponse post = httpRequest.post("http://" + url + "/api/hrm/kq/attendanceButton/punchButton", map1);
        String msg = EntityUtils.toString(post.getEntity());
        EmailSender.send(true,"[" + sdf.format(new Date()) + "]上班打卡:\n" + msg, user.getEmail());
        logger.info("用户[{}]上班打卡[{}]", user.getName(), msg);

    }

    public void outSign() throws Exception {
        if (!isWorkDay) {
            return;
        }
        try {
            Map<String, Object> map1 = new HashMap<>();
            String format = sdf.format(new Date());
            String formatAdd1 = sdf.format(System.currentTimeMillis() + (3600 * 24 * 1000));
            String sid = user.getSid();
            String mac = user.getMac();
            map1.put("date", format);
            map1.put("belongtime", "17:30");
            map1.put("type", "off");
            map1.put("canSignTime", "00:00");
            map1.put("across", 0);
            map1.put("belongdate", format);
            map1.put("datetime", format + " 17:30:00");
            map1.put("min", "390");
            map1.put("islastsign", "1");
            map1.put("signSectionTime", formatAdd1 + " 00:00:59");
            map1.put("signSectionBeginTime", "");
            map1.put("isYellow", "1");
            map1.put("isPunchOpen", "1");
            map1.put("isacross", "0");
            map1.put("pre", "0");
            String signTime = sdf2.format(System.currentTimeMillis());
            map1.put("signTime", signTime);
            map1.put("signSection", format + " 00:01:00#" + formatAdd1 + " 00:00:59");
            map1.put("signbelongspan", "今天");
            map1.put("active", "0");
            map1.put("needSign", "0");
            map1.put("workmins", "450");
            map1.put("signbelong", "今天");
            map1.put("reSign", "1");
            map1.put("min_next", "-1");
            map1.put("signfrom", "e9mobile");
            map1.put("serialid", "1");
            map1.put("signAcross", "1");
            map1.put("signAcross_next", "0");
            map1.put("time", "17:30");
            map1.put("position", "福建省厦门市集美区诚毅北大街55号靠近厦门国信信用大数据创新研究院");
            map1.put("longitude", String.valueOf(118.04448) + String.valueOf(random.nextInt(784321787)));
            map1.put("latitude", String.valueOf(24.61422) + String.valueOf(random.nextInt(2068608887)));
            map1.put("locationid", "6");
            map1.put("locationshowaddress", "1");
            map1.put("sid", sid);
            map1.put("mac", mac);
            map1.put("deviceId", "863064396916522");
            map1.put("deviceInfo", "{\"errCode\":0,\"errMsg\":\"getClientInfo:ok\",\"clientType\":\"3\",\"clientVersion\":\"7.0.37.20200806\",\"deviceId\":\"863064396916522\",\"osVersion\":25,\"clientModel\":\"Xiaomi,MI 9\",\"clientFont\":\"1\",\"clientTheme\":\"#393F9D\",\"clientLang\":\"zh\",\"networkType\":\"wifi\",\"BSSID\":\"" + mac + "\",\"SSID\":\"" + mac + "\"}");
            map1.put("browser", "EMobile");
            map1.put("_ec_ismobile", "true");
            map1.put("_ec_browser", "EMobile");
            map1.put("_ec_browserVersion", "7.0.37.20200806");
            map1.put("_ec_os", "Android");
            map1.put("_ec_osVersion", "7.1.2");
            map1.put("ismobile", "1");
            CloseableHttpResponse post = httpRequest.post("http://" + url + "/api/hrm/kq/attendanceButton/punchButton", map1);
            String msg = EntityUtils.toString(post.getEntity());
            logger.info("用户[{}]下班打卡[{}]", user.getName(), msg);
            EmailSender.send(true,"[" + sdf.format(new Date()) + "]下班打卡:\n" + msg, user.getEmail());
        } catch (Exception e) {
            logger.error("用户[{}]打卡异常", user.getName());
            EmailSender.send(false,"[" + sdf.format(new Date()) + "]下班打卡失败:\n" + e.getMessage(), user.getEmail());
        }
    }

}
